package logic

import (
	"context"
	"fmt"
	"log/models/cache"
	"log/models/mysql"
	"log/pkg"

	"log/logrpc/internal/svc"
	"log/logrpc/logrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *logrpc.LoginRequest) (*logrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在")
	}
	res1, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Account).Result()
	if in.SendSmsCode != res1 {
		return nil, fmt.Errorf("短信验证码错误")
	}
	res2, _ := cache.RDB.Get(l.ctx, "captcha"+in.Account).Result()
	if in.CaptchaImage != res2 {
		return nil, fmt.Errorf("图形验证码错误")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}
	return &logrpc.LoginResponse{}, nil
}
